from .scope import Scope
from .container import Container

class ForBlock(Container):
    
    def __init__(self, items_name, item_name='', filter_=None):
        Container.__init__(self)
        self.__items_name = items_name
        self.__item_name = item_name
        self.__filter = filter_
    
    def render(self, scope):
        
        lines = []
        for_scope = Scope(scope)
        items = scope.lookup(self.__items_name)
        
        if self.__filter is None:
            filtered_items = items
        else:
            filtered_items = []
            for item in items:
                if self.__item_name:
                    for_scope.define_symbol(self.__item_name, item)
                if self.__filter.is_true(for_scope):
                    filtered_items.append(item) 
        
        num_items = len(filtered_items)
        
        for num, item in enumerate(filtered_items):
            if self.__item_name:
                for_scope.define_symbol(self.__item_name, item)
            for_scope.define_symbol('::IS_FIRST', num == 0)
            for_scope.define_symbol('::IS_LAST', num == num_items - 1)
            for block in self._body:
                lines += block.render(for_scope)
        
        return lines